package com.adroiti.texasholdem.engine.combinations;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.adroiti.texasholdem.Card;

public class Straight extends AbstractCombination {

	private High high;

	public Straight() {
		this(new High());
	}

	public Straight(High high) {
		this.high = high;
	}

	@Override
	public int getRank(List<Card> player, List<Card> table) {

		List<Card> cards = clearedStraightList(player, table);
		
		int num = 0;
		for (int i = 0; i < cards.size() - 1; i++) {
			if (num == 0 && i + 4 > cards.size()) {
				return 0;
			}
			if ((cards.get(i).getRank() + 1) == cards.get(i + 1).getRank()) {
				num++;
			} else
				num = 0;
		}
		
		if(num < 4){
			return 0;
		}

		return this.high.getRank(player, table);
	}

	private List<Card> clearedStraightList(List<Card> player, List<Card> table) {
		List<Card> cards = new ArrayList<Card>(player);
		cards.addAll(table);

		Collections.sort(cards);
		
		for(int i = 0; i < cards.size() - 1;){
			if(cards.get(i).getRank() == cards.get(i+1).getRank()){
				cards.remove(i + 1);
			}
			else i++;
		}
		return cards;
	}

	@Override
	public String getName() {
		return "Straight";
	}

	@Override
	public int getCombinationRank() {
		return 5;
	}

}
